package cn.com.ctcloud.microservice.dynamicds.filter;

import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.com.ctcloud.microservice.dynamicds.OrganCodeHolder;
import lombok.extern.slf4j.Slf4j;

/**
 * Title: 分布式动态数据源路由
 * <p>
 * Description: 服务请求拦截器
 * <p>
 * Copyright: Copyright (c) 2008
 * <p>
 * Company: Liaoning Open Data Communication Co.,Ltd.
 * 
 * @author lihui
 * @version 1.0.0
 */
@Slf4j
public class OrganCodeInterceptor implements HandlerInterceptor {
	private String organCodeHeaderName = "organCode";

	private Set<String> validOrgCodes;

	public void setOrganCodeHeaderName(String organCodeName) {
		organCodeHeaderName = organCodeName;
	}

	public void setValidOrgCodes(Set<String> validOrgCodes) {
		this.validOrgCodes = validOrgCodes;
	}

	/**
	 * 在服务请求执行前执行，它负责析取请求header中的orgCode(机构码)，并把它塞入ThreadLocal全局变量中
	 */
	@Override
	public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
			throws Exception {
		log.info("preHandle被调用");
		String orgCodeVal = httpServletRequest.getHeader(organCodeHeaderName);
		if (orgCodeVal == null) {
			log.error("The request without a header named as " + organCodeHeaderName);
			return false;
		}
		if (!validOrgCodes.contains(orgCodeVal)) {
			log.error(String.format(" the organCode %s is not valid.", orgCodeVal));
			return false;
		}
		OrganCodeHolder.putOrganCode(httpServletRequest.getHeader(organCodeHeaderName));
		return true;
	}

	/**
	 * 负责在服务请求执行后（就算服务抛出异常也会被执行），主要是清除ThreadLocal全局变量中的内容，为下一个请求到来做准备
	 */
	@Override
	public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
			ModelAndView modelAndView) throws Exception {
		log.info("postHandle被调用");
		OrganCodeHolder.remove();
	}

}
